
// import toAppSuccess from './toAppSuccess'

// toAppSuccess()

// import details from './grabDetails'

// details('100038rbdmdb')
// details('10002scw3j37')

// import model from './model'

// model.all().then(async result => {
// for (let i = 0; i < result.length; i++) {
// const element = result[i]
// await details(element.id)
// }
// })

import '@/config'

import path from 'path'

import Koa from 'koa'
import Router from 'koa-router'
import Static from 'koa-static'
import bodyParser from 'koa-bodyparser'
import WebSocket from 'ws'

import event from '@/lib/event'

import model from '@/model'
import login from '@/login'
import toAppSuccess from '@/toAppSuccess'
import toAppFailure from '@/toAppFailure'
import toAppIncomplete from '@/toAppIncomplete'
import toAppAudit from '@/toAppAudit'
import grabDetails from '@/grabDetails'

const app = new Koa()
var router = new Router()

router.get('/task', async (ctx, next) => {
  console.log(ctx.query.type)
  // toAppSuccess()
  if (ctx.query.type === 'toAppSuccess') {
    model.sequelize.query('select auditingTime from users where grabPosition = "toAppSuccess" order by auditingTime desc limit 1').spread((results, metadata) => {
      toAppSuccess(results.length > 0 ? results[0].auditingTime : undefined)
    })
  } else if (ctx.query.type === 'toAppFailure') {
    // model.sequelize.query('select auditingTime from users where grabPosition = "toAppFailure" order by auditingTime desc limit 1').spread((results, metadata) => {
    //   toAppFailure(results.length > 0 ? results[0].auditingTime : undefined)
    // })
    toAppFailure()
  } else if (ctx.query.type === 'incomplete') {
    // model.sequelize.query('select registerTime from users where grabPosition = "toAppIncomplete" order by registerTime desc limit 1').spread((results, metadata) => {
    //   toAppIncomplete(results.length > 0 ? results[0].auditingTime : undefined)
    // })
    toAppIncomplete()
  } else if (ctx.query.type === 'toAppAudit') {
    // model.sequelize.query('select registerTime from users where grabPosition = "toAppAudit" order by registerTime desc limit 1').spread((results, metadata) => {
    //   toAppAudit(results.length > 0 ? results[0].auditingTime : undefined)
    // })
    toAppAudit()
  } else if (ctx.query.type === 'images') {
    model.sequelize.query('select id from users where grabPosition = "toAppSuccess" and (again = 1 or idCardImage is null or drivingLicenceImage is null)').spread(async (results, metadata) => {
      event.emit('total', results.length)
      for (let i = 0; i < results.length; i++) {
        const element = results[i]
        await grabDetails(element.id)
        event.emit('processed')
      }
    })
  }
  ctx.body = ''
}).get('/verifyCode', async (ctx, next) => {
  ctx.body = await login.checkImage()
}).post('/login', async (ctx, next) => {
  const response = await login.login(ctx.request.body.params)
  ctx.body = response
})

app.use(bodyParser()).use(router.routes()).use(Static(path.join(__dirname, '..', 'static'), { extensions: ['html'] }))

app.listen('3000')

console.log('服务启动成功，端口号：3000')

const WebSocketServer = WebSocket.Server
const wss = new WebSocketServer({
  port: 3001
})

const clients = []

const data = {
  total: 0,
  processed: 0,
  status: 'logout'
}

wss.on('connection', (ws) => {
  const index = clients.length
  clients.push(ws)
  ws.send(JSON.stringify(data))
  ws.on('close', () => {
    clients.splice(index, 1)
  })
})

event.on('logout', () => {
  data.status = 'logout'
  clients.forEach(it => {
    it.send(JSON.stringify(data))
  })
})

event.on('login', () => {
  data.status = 'login'
  clients.forEach(it => {
    it.send(JSON.stringify(data))
  })
})

event.on('total', (value) => {
  data.total = value
  data.processed = 0
  clients.forEach(it => {
    it.send(JSON.stringify(data))
  })
})

event.on('processed', () => {
  data.processed += 1
  clients.forEach(it => {
    it.send(JSON.stringify(data))
  })
})
